package com.yin97.kotiln

import android.util.Log
import com.yin97.kotiln.app.App
import okhttp3.Cache
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory
import retrofit2.converter.gson.GsonConverterFactory
import retrofit2.converter.scalars.ScalarsConverterFactory
import java.io.File

/**
 * Created by meishiyiyun on 2017/5/25.
 */

class  RetrofitHelper{
    companion object {
        @Volatile var instance: RetrofitHelper? = null
            get() {
                if (field == null) {
                    synchronized(RetrofitHelper::class.java) {
                        if (field == null)
                            field = RetrofitHelper()
                    }
                }
                return field
            }
    }

    fun  createScaHttp (): RetrofitService {
        var  retrofit = Retrofit.Builder()
                .baseUrl("http://gank.io/api/")
                .client(createClient())
                .addConverterFactory(ScalarsConverterFactory.create())
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create()).build();
      return retrofit.create(RetrofitService::class.java);

  }


    fun  createGsonHttp (): RetrofitService {
        var  retrofit = Retrofit.Builder()
                .baseUrl("http://gank.io/api/")
                .client(createClient())
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create()).build();
        return retrofit.create(RetrofitService::class.java);

    }

    private fun  createClient() : OkHttpClient{
        var  builder =OkHttpClient.Builder();
        val SIZE_OF_CACHE = (10 * 1024 * 1024).toLong();
        val cacheFile =File(App.instance.cacheDir,"http")
        var  cache=Cache(cacheFile,SIZE_OF_CACHE)
        builder.cache(cache);
        builder.addInterceptor(provideInterceptor());

        return builder.build();
    }
fun  provideInterceptor() :HttpLoggingInterceptor{
    val interceptor = HttpLoggingInterceptor{
        msg -> Log.d("okhttp",msg)
    }
    interceptor.level = HttpLoggingInterceptor.Level.BODY
    return interceptor
}
    }



